<template>
  <div class="container">
    <div class="form-section">
<!--    <h2>Health Data Submission Form</h2>-->
    <h1>欢迎使用，{{ userName }}</h1>
    <el-form ref="formRef" :model="formData" label-width="120px" @submit.prevent="submitHealthData" class="health-form">
      <el-form-item label="性别" prop="gender" :rules="[{ required: true, message: '请选择性别', trigger: 'change' }]">
        <el-select v-model="formData.gender" placeholder="请选择">
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age" :rules="[{ required: true, message: '请输入年龄', trigger: 'blur' }]">
        <el-input v-model.number="formData.age" type="number" placeholder="输入年龄"></el-input>
      </el-form-item>
      <el-form-item label="身高 (cm)" prop="height" :rules="[{ required: true, message: '请输入身高', trigger: 'blur' }]">
        <el-input v-model.number="formData.height" type="number" placeholder="输入身高"></el-input>
      </el-form-item>
      <el-form-item label="体重 (kg)" prop="weight" :rules="[{ required: true, message: '请输入体重', trigger: 'blur' }]">
        <el-input v-model.number="formData.weight" type="number" placeholder="输入体重"></el-input>
      </el-form-item>
      <el-form-item label="收缩压 (ap_hi)" prop="ap_hi" :rules="[{ required: true, message: '请输入收缩压', trigger: 'blur' }]">
        <el-input v-model.number="formData.ap_hi" type="number" placeholder="输入收缩压"></el-input>
      </el-form-item>
      <el-form-item label="舒张压 (ap_lo)" prop="ap_lo" :rules="[{ required: true, message: '请输入舒张压', trigger: 'blur' }]">
        <el-input v-model.number="formData.ap_lo" type="number" placeholder="输入舒张压"></el-input>
      </el-form-item>
      <el-form-item label="胆固醇" prop="cholesterol" :rules="[{ required: true, message: '请选择胆固醇水平', trigger: 'change' }]">
        <el-select v-model="formData.cholesterol" placeholder="请选择">
          <el-option label="正常" value="1"></el-option>
          <el-option label="高于正常" value="2"></el-option>
          <el-option label="远高于正常" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="葡萄糖" prop="gluc" :rules="[{ required: true, message: '请选择葡萄糖水平', trigger: 'change' }]">
        <el-select v-model="formData.gluc" placeholder="请选择">
          <el-option label="正常" value="1"></el-option>
          <el-option label="高于正常" value="2"></el-option>
          <el-option label="远高于正常" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否吸烟" prop="smoke">
        <el-checkbox v-model="formData.smoke"></el-checkbox>
      </el-form-item>
      <el-form-item label="是否喝酒" prop="alco">
        <el-checkbox v-model="formData.alco"></el-checkbox>
      </el-form-item>
      <el-form-item label="是否活跃" prop="active">
        <el-checkbox v-model="formData.active"></el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="submitHealthData">提交</el-button>
        <el-button type="primary" @click="goToHistory">查询历史预测记录</el-button>
      </el-form-item>
    </el-form>
    </div>

    <div class="info-section">
      <el-card class="info-card">
        <h2>网站介绍</h2>
        <p>本网站是一个人工智能驱动的平台，专注于预测患病概率和进行健康评估。用户可以通过输入个人健康数据，获取潜在健康风险的评估，以便采取适当的健康管理措施。</p>
        <h3>健康小建议</h3>
        <ul>
          <li v-for="advice in selectedAdvices" :key="advice">{{ advice }}</li>
        </ul>
      </el-card>
    </div>

  </div>
</template>

<script setup>
import { ref,computed } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router'

const username = ref('')

const advices = [
  '每天至少喝8杯水',
  '保持每天至少30分钟的运动',
  '尽量多吃蔬菜和水果',
  '每天保证足够的睡眠',
  '定期进行身体检查'
];


const storedUsername = ref(localStorage.getItem('username'));

const userName = computed(() => {
  return storedUsername.value ? storedUsername.value : '访客';
});

const router = useRouter()

const formData = ref({
  gender: '',
  age: null,
  height: null,
  weight: null,
  ap_hi: null,
  ap_lo: null,
  cholesterol: '',
  gluc: '',
  smoke: false,
  alco: false,
  active: false
});

const validateInput = () => {
  let errorMessage = '';
  if (!formData.value.gender) {
    errorMessage += '性别不能为空。\n';
  }
  if (!formData.value.age) {
    errorMessage += '年龄不能为空。\n';
  }
  if (!formData.value.height) {
    errorMessage += '身高不能为空。\n';
  }
  if (!formData.value.weight) {
    errorMessage += '体重不能为空。\n';
  }
  if (!formData.value.ap_hi) {
    errorMessage += '收缩压不能为空。\n';
  }
  if (!formData.value.ap_lo) {
    errorMessage += '舒张压不能为空。\n';
  }
  if (!formData.value.cholesterol) {
    errorMessage += '胆固醇不能为空。\n';
  }
  if (!formData.value.gluc) {
    errorMessage += '葡萄糖不能为空。\n';
  }

  if (formData.value.ap_hi < 50 || formData.value.ap_hi > 200) {
    errorMessage += '收缩压必须在50到200毫米汞柱之间。\n';
  }
  if (formData.value.ap_lo < 40 || formData.value.ap_lo > 150) {
    errorMessage += '舒张压必须在40到150毫米汞柱之间。\n';
  }
  if (formData.value.height < 140 || formData.value.height > 210) {
    errorMessage += '身高必须在140到210厘米之间。\n';
  }
  if (formData.value.weight < 35 || formData.value.weight > 120) {
    errorMessage += '体重必须在35到120千克之间。\n';
  }
  if (formData.value.age < 0 || formData.value.age > 110) {
    errorMessage += '年龄必须在0到110岁之间。\n';
  }

  if (errorMessage) {
    alert('请检查您的输入：\n' + errorMessage);
    return false;
  }
  return true;
};

const submitHealthData = async () => {
  if(!validateInput()){
    return;
  }
  const dataToSubmit = {
    ...formData.value,
    smoke: formData.value.smoke ? 1 : 0,
    alco: formData.value.alco ? 1 : 0,
    active: formData.value.active ? 1 : 0
  };

  try {
    const response = await axios.post('http://localhost:5000/api/predict', dataToSubmit,
        {
          withCredentials: true
        });
    // localStorage.setItem('username', )
    console.log("response:", response)
    console.log("response.data:", response.data)
    await router.push({
          name: 'healthdata',
          query: {
            result: response.data.result,
            advice: JSON.stringify(response.data.advice)
          }
        }
    )
    console.log('Data submitted successfully! Result: ' + response.data.result);
  } catch (error) {
    alert('Error submitting data: ' + (error.response.data.message || error.message));
  }
};

const checkLoginStatus = async () => {
  const storedUsername = localStorage.getItem('username');
  return storedUsername !== null;
};

const logout = () => {
  axios.post('http://localhost:5000/api/logout', {}, {
    withCredentials: true,
    headers: {
      'Content-Type': 'application/json'
    }
  })
      .then(response => {
        const { message, status } = response.data;
        proxy({
          message: message,
          type: status === 'success' ? 'success' : 'error',
          duration: 5000
        });

        if (response.status === 200) {
          localStorage.removeItem('username');
          router.push('/login');
          console.log('退出登录成功');
        }
      })
      .catch(error => {
        console.error('请求失败：', error);
        if (error.response) {
          proxy({
            message: error.response.data.message || '请求失败',
            type: 'error',
            duration: 5000
          });
        } else {
          proxy({
            message: '网络错误或服务器未响应',
            type: 'error',
            duration: 5000
          });
        }
      });
};

const goToHistory = async () => {
  const isLoggedIn = await checkLoginStatus();
  if (isLoggedIn) {
    await router.push('/history');
  } else {
    alert('登录状态已过期，请重新登录。');
    await router.push('/login');
  }
};

const selectedAdvices = computed(() => {
  return advices.sort(() => 0.5 - Math.random()).slice(0, 3);
});

</script>

<style>
.form-group {
  margin-bottom: 1rem;
}
label {
  display: block;
}
input[type="number"], select {
  width: 100%;
  padding: 8px;
  margin-top: 0.5rem;
}
button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
button:hover {
  background-color: #0056b3;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f3e2e3;
}

.form-section {
  flex: 1;
  margin-right: 10px;
}

.info-section {
  flex: 1;
  max-width:600px;
}

.health-form .el-form-item {
  width: 800px;
}

.info-card {
  position: sticky;
  top: 20px;
}
</style>